//////////////////////////////////////////////////
// EASIM project
// easim.net.RateChecker
// 6/19/2007 8:29 PM
// Cong Liu
// gzcong@gmail.com

// Copyright (C) 2007
// All rights reserved.
// Refer to LICENSE of JIST (Java In Simulation Time) for terms and conditions of use.

package easim.omar;

import easim.net.Clock;
import easim.net.Timer;

import jist.runtime.JistAPI.DoNotRewrite;

public abstract class RateChecker implements Timer, DoNotRewrite
{
  protected long bound;
  protected int events;
  protected long[] times;
  protected int count;

  public RateChecker(int events, long bound) {
    this.events = events;
    this.bound = bound;
    times = new long[events];
    count = 0;
  }

  public void schedule() {
    long delay = 0;
    if (count == events) {
      long curTime = Clock.getTime();
      delay = bound - (curTime - times[0]);
      if (delay < 0) delay = 0;
    }
    Clock.start(this, delay, false);
  }

  public void addTime() {
    long curTime = Clock.getTime();
    if (count < events) {
      times[count] = curTime;
      ++ count;
    }
    else {
      for (int i = 0; i < times.length - 1; ++ i) {
        times[i] = times[i + 1];
      }
      times[times.length - 1] = curTime;
    }
  }

}
